package cn.sdormitory.violative.service;


import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.Assert;
import cn.hutool.json.JSONObject;
import cn.sdormitory.basedata.dao.BClassDao;
import cn.sdormitory.basedata.dao.BStudentDao;
import cn.sdormitory.smartclass.service.ClassDvService;
import cn.sdormitory.sys.dao.SysDeptDao;
import cn.sdormitory.sys.dao.SysUserDao;
import cn.sdormitory.sys.service.SysUserRoleService;
import cn.sdormitory.sys.service.SysUserService;
import cn.sdormitory.sys.vo.WechatNotifyClassTeacherInfo;
import cn.sdormitory.violative.dao.ViolationClassIntervalDao;
import cn.sdormitory.violative.entity.ViolationClassInterval;
import cn.sdormitory.violative.form.ViolationClassIntervalQueryForm;
import cn.sdormitory.violative.form.ViolationClassIntervalReceiveForm;
import cn.sdormitory.violative.form.ViolationClassIntervalSaveForm;
import cn.sdormitory.wx.entity.WechatPushMessage;
import cn.sdormitory.wx.mapper.WechatPushMessageMapper;
import cn.sdormitory.wx.utils.WXUtil;
import cn.sdormitory.wx.utils.WeatherDataCreator;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ViolationClassIntervalServiceImpl extends ServiceImpl<ViolationClassIntervalDao, ViolationClassInterval> implements ViolationClassIntervalService {
    @Resource
    private SysUserService userService;
    @Resource
    private WXUtil wxUtil;
    @Resource
    private WeatherDataCreator weatherDataCreator;
    @Resource
    private WechatPushMessageMapper wechatPushMessageMapper;
    
    private static final String WECHAT_TEMPLATE = "embMMz-4Swbohiid3q8FlEPOA9HKC-oJ6sSka-sNbw4";

    @Override
    public IPage<ViolationClassInterval> pageList(ViolationClassIntervalQueryForm queryForm) {
        QueryWrapper<ViolationClassInterval> wrapper = queryForm.queryOrderByDescId();
        return page(queryForm.generatePage(), wrapper);
    }

    @Override
    public ViolationClassInterval getDetail(long id) {
        return getById(id);
    }

    @Override
    public void save(ViolationClassIntervalSaveForm form) {
        ViolationClassInterval violationClassInterval = form.generateViolationClassInterval();
        boolean notifyTeacher;
        if(violationClassInterval.getId() != null){
            ViolationClassInterval oldViolationClassInterval = getOne(Wrappers.lambdaQuery(ViolationClassInterval.class)
                    .select(ViolationClassInterval::getId, ViolationClassInterval::getClassId)
                    .eq(ViolationClassInterval::getId, violationClassInterval.getId())
            );
            Assert.notNull(oldViolationClassInterval,"该课间违纪不存在");
            updateById(violationClassInterval);
            // 修改了班级需要通知
            notifyTeacher = !Objects.equals(oldViolationClassInterval.getClassId(), violationClassInterval.getClassId());
        }else {
            save(violationClassInterval);
            notifyTeacher = true;
        }
        if(notifyTeacher){
            notifyTeachers(violationClassInterval);
        }
    }

    @Override
    public void receiveStudents(ViolationClassIntervalReceiveForm form) {
        Assert.notEmpty(form.getStudentIds(),"学生编号列表不能为空");
        Assert.notNull(form.getId(),"课间违纪编号不能为空");
        Assert.notBlank(form.getHandleContent(),"处理内容不能为空");
        String studentIdsStr = form.getStudentIds().stream().map(Convert::toStr).collect(Collectors.joining(","));
        update(Wrappers.<ViolationClassInterval>lambdaUpdate()
                .eq(ViolationClassInterval::getId,form.getId())
                .set(ViolationClassInterval::getStudentIds, studentIdsStr)
                .set(ViolationClassInterval::getHandleContent, form.getHandleContent())
                .set(ViolationClassInterval::getStudentNum, form.getStudentIds().size())
        );
    }

    private void notifyTeachers(ViolationClassInterval violationClassInterval) {
        WechatNotifyClassTeacherInfo teacherInfo = userService.getWechatNotifyClassTeacherInfo(violationClassInterval.getClassId());
        if(teacherInfo == null){
            return;
        }
        Map<String, Object> data = weatherDataCreator.createViolationPatrolData("未知学生",violationClassInterval.getViolationTime());
        WechatPushMessage wechatPushMessage = new WechatPushMessage();
        wechatPushMessage.setTemplateId(WECHAT_TEMPLATE);
        wechatPushMessage.setContent(data.toString());
        wechatPushMessage.setReceiverOpenId(teacherInfo.getTeacherWechatOpenId());
        boolean success;
        String errorMessage;
        try{
            JSONObject jsonObject = wxUtil.sendInfo(teacherInfo.getTeacherWechatOpenId(), WECHAT_TEMPLATE, data, "pages_duty/classTeacher/violation/violationClassIntervalDetail?id="+violationClassInterval.getId());
            if (jsonObject != null && "0".equals(jsonObject.get("errcode").toString())) {
                // 发送成功
                success = true;
            } else {
                success = false;
            }
            errorMessage = jsonObject.get("errmsg").toString();
        }catch (Exception e){
            success = false;
            errorMessage = e.getMessage();
            log.error("通知班主任认领课间违纪异常 异常消息为{}",e.getMessage());
        }
        wechatPushMessage.setStatus(success);
        wechatPushMessage.setBackInfo(errorMessage);
        wechatPushMessageMapper.insert(wechatPushMessage);
    }
}
